package com.stylefeng.web.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.modular.shop.service.*;
import com.stylefeng.guns.persistence.shop.model.*;
import com.stylefeng.web.utils.MemberUtils;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Controller
@RequestMapping("/person")
public class PersonController {
    private String PREFIX = "/web/";
    @Resource
    ITStoreService itStoreService;
    @Resource
    ITMemberService itMemberService;
    @Resource
    ITGoodsService itGoodsService;
    @Resource
    ITCartService itCartService;
    @Resource
    ITOrderService itOrderService;
    /**
     * 开店
     */

    @RequestMapping(value = "addStore", method = RequestMethod.GET)
    public String addStore(Model model) {
        TMember tMember = MemberUtils.getSessionLoginUser();
        if (tMember!=null && tMember.getStoreid()!=null){
            TStore store = itStoreService.selectById(tMember.getStoreid());
            model.addAttribute("store",store);
            return PREFIX + "store.html";
        }else{
            return PREFIX + "addStore.html";
        }

    }
    @RequestMapping(value = "addStore", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> addStores(TStore tStore,
                                   HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();
        TMember tMember = MemberUtils.getSessionLoginUser();
        if (tMember!=null) {
            tStore.setAddTime(new Date());
            itStoreService.insert(tStore);
            tMember.setStoreid(tStore.getId());
            itMemberService.updateById(tMember);
            map.put("code","1");
            map.put("id",tStore.getId());
        }else {
            map.put("code","2");
        }
        return map;
    }


    @RequestMapping(value = "addGoods", method = RequestMethod.GET)
    public String addGoods() {
        TMember tMember = MemberUtils.getSessionLoginUser();
        if (tMember!=null && tMember.getStoreid()!=null) {
            return PREFIX + "addGoods.html";
        }else{
            return PREFIX + "login.html";
        }
    }
    @RequestMapping(value = "addGoods", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> addGoods(TGoods tGoods,
                                  HttpServletRequest req) {
        Map<String, Object> map = new HashMap<>();

        TMember tMember = MemberUtils.getSessionLoginUser();
        if (tMember!=null) {
//            String imges="";
//            String blogInfo=tGoods.getRemark();
//            Document doc=Jsoup.parse(blogInfo);
//            Elements jpgs=doc.select("img[src]"); //　查找扩展名是jpg的图片
//            for(int i=0;i<jpgs.size();i++){
//                Element jpg=jpgs.get(i);
//                if(jpg!=null && jpg!=null){
//                    String linkHref = jpg.attr("src");
//                    imges+=linkHref+",";
//                }
//                if(i==2){
//                    break;
//                }
//            }
            tGoods.setStoreid(tMember.getId());
          //  tGoods.setImgmore(imges);
            tGoods.setCreateDate(new Date());
            tGoods.setCreateBy(tMember.getId());
            itGoodsService.insert(tGoods);
            map.put("id",tMember.getId());
            map.put("code","1");
        }else {
            map.put("code","2");
        }
        return map;
    }

    /**
     * 加入购物车
     * @param goodsid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addCart", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, String> addCart(@RequestParam(value = "goodsid") Long goodsid) throws Exception {
        TGoods goods=itGoodsService.selectById(goodsid);
        TCart cart=new TCart();
        cart.setGoodsid(goodsid);
        cart.setUserid(MemberUtils.getSessionLoginUser().getId());
        TCart check=itCartService.selectOne(new EntityWrapper<>(cart));
        Map<String, String> map = new HashMap<>();
        Boolean result= false;
        if(check==null){
            cart.setCount(1);
            cart.setGoodsname(goods.getTitle());
            cart.setImg(goods.getImg());
            cart.setPrice(goods.getPrices());
            cart.setStoreid(goods.getStoreid());
            result = itCartService.insert(cart);
        }else{
            check.setCount(check.getCount()+1);
            result=itCartService.updateById(check);
        }

        if(result){
            map.put("success", "true");
        }else{
            map.put("success", "false");
        }
        return map;
    }
    /**
     * 删除购物车
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deleteCart", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, String> deleteCart(@RequestParam(value = "id") Long id) throws Exception {
        itCartService.deleteById(id);
        Map<String, String> map = new HashMap<>();
        map.put("success", "true");
        return map;
    }
    /**
     * 立即购买
     * @param ProductId
     * @return
     * @throws Exception
     */
    @RequestMapping("/LikBuy/{ProductId}")
    public ModelAndView ProductDetail(@PathVariable("ProductId") Long ProductId,
                                      HttpSession session)throws Exception{
        ModelAndView mav=new ModelAndView();
//			 Product goods=ProductService.selectByPrimaryKey(ProductId);
//			Cart cart=new Cart();
//		 	cart.setGoodsid(ProductId);
//		 	cart.setUserid(SysUserUtils.getSessionLoginUser().getId());
//		 	Cart check=CartService.selectOne(cart);
//		 	Map<String, String> map = Maps.newHashMap();
//		 	int result=0;
//		 	if(check==null){
//		 		cart.setCount(1);
//		 		cart.setGoodsname(goods.getTitle());
//			 	cart.setPrice(goods.getPrices());
//				 result = CartService.insertSelective(cart);
//		 	}else{
//		 		check.setCount(check.getCount()+1);
//		 		result=CartService.updateByPrimaryKeySelective(check);
//		 	}

        TCart cart1 = new TCart();
        cart1.setUserid(MemberUtils.getSessionLoginUser().getId());
        List<TCart> cartList=itCartService.selectList(new EntityWrapper<>(cart1));
        mav.addObject("cartList", cartList);

//        List<Address> addressList= AddressService.selectByMemberId();
//        mav.addObject("addressList", addressList);

//        TPayment Payment=new Payment();
//        Payment.setIsDel(1);
//        List<Payment> payList=PaymentService.select(Payment);
//        mav.addObject("payList", payList);

        mav.setViewName("mall/LikBuy");
        return mav;
    }
    /**
     * 提交订单
     * @param cartIds
     * @return
     * @throws Exception
     */
    @RequestMapping("submitOrder")
    public ModelAndView submitOrder(@RequestParam(value = "cartIds") String[] cartIds,
                                    @RequestParam(value = "addressid") Long addressid,
                                    @RequestParam(value = "paymentid") Long paymentid,
                                    @RequestParam(value = "paymentid",defaultValue="无留言") String usercontent
    )throws Exception{
        ModelAndView mav=new ModelAndView();
        TOrder order=itOrderService.insertOrder(cartIds,addressid,paymentid,usercontent);
//        Payment Payment=new Payment();
//        Payment.setIsDel(1);
//        List<Payment> payList=PaymentService.select(Payment);
//        mav.addObject("payList", payList);
        if(order==null){
            mav.setViewName("mall/forwad");
        }else{
            mav.setViewName("mall/success");
        }

        mav.addObject("order", order);
        return mav;
    }

}
